package com.hsy.crm.web.utils;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.Random;

public class UuidUtils {

    private UuidUtils(){}

    private static final Random RANDOM = new Random();

    private static final int BOUND = 1000000;

    private static long MILLIS = -1;

    private static List<Integer> RANDOMS = Lists.newArrayList();

    /**
     * TODO 同时连续生成时避免重复
     * @return
     */
    public static Long getUuid() {
        long millis = DateUtils.millis();
        if( millis != MILLIS ){
            MILLIS = millis;
            RANDOMS.clear();
        }

        String random = getRandom();
        return Long.parseLong(millis + random);
    }

   private static String getRandom(){
       int random = RANDOM.nextInt(BOUND);

       while(isExists(random)){
           random = RANDOM.nextInt(BOUND);
       }

       RANDOMS.add(random);

       return String.format("%06d", random);
   }

   private static boolean isExists(int random){
        for( int ran : RANDOMS ){
            if( ran == random ){
                return true;
            }
        }
        return false;
   }

}
